package com.tenement.netty.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.tenement.entity.Chat;
import com.tenement.entity.ChatModel;
import com.tenement.netty.service.ChatHandlerService;
import com.tenement.service.ChatService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.sql.Timestamp;
import java.util.*;

public class RadioServiceImpl implements ChatHandlerService {

    private ChatService chatService = SpringUtil.getBean(ChatService.class);

    @Override
    public void execute(ChatModel chatModel, ChannelHandlerContext channelHandlerContext, Map<String, Channel> privateChannel, Set<Channel> channelGroups) {
        chatModel.setType((short) 3).setSendTime(new Timestamp(new Date().getTime()));
        List<Chat> chats = new ArrayList<>();
        privateChannel.forEach( (key,value) -> {
            if( value.id() != channelHandlerContext.channel().id() ) {
                value.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(chatModel)));
                chats.add(new Chat().setTarget(Long.valueOf(key)).setMsg(chatModel.getMsg()).setSendTime(chatModel.getSendTime()).setType(chatModel.getType()));
            }
        });
        if( chats.size() > 0 ) {
            chatService.saveBatch(chats);
        }
    }
}
